<!doctype html public "html2.0">
<html>
<head>
<title>The TSpaces Examples</title>
<!-- created by: Toby Lehman, 25-Jan-1998 -->
<meta name="abstract" content="TSpaces Examples ">
<meta name="keywords" content="TSpaces Java TupleSpace Database">
<meta name="owner"    content="toby@almaden.ibm.com">
<meta name="review"   content="19980125">
<meta name="security" content="public">
</head>

<! Set white background with red and purple links ->
<body bgcolor="#ffffff" text="#000000" link="#CC0000" alink="#ff3300" vlink="#330099">
<! Include the Masthead -> 
<center>
<img src="gifs/masthead.gif" alt="TSpaces" ALIGN = "middle" BORDER = 0 width=600 height=54>
     
</center>


<center>
<H1>The TSpaces Examples </H1>
</center>
<br clear=right>
 

<P>We have included a number of sample programs with the TSpaces package.
These examples are not intended as complete useful application but rather
each one is intended to show the use of one or more features.&nbsp; The
source for each sample is distributed along with the pre compiled class
file and one or more shell scripts that will invoke the sample.

<P>In the following examples, I will assume that you are running on Win95 or NT.
OS/2 users will need to rename the *.bat files to *.cmd.
We have provided a limited number of *.sh scripts for Unix users.
Unix users will have to make the necessary translations for their
cmdline environment.  We would like to distribute whatever is needed to implement 
Mac support and would welcome a volunteer to help us with this. 

<p>
The included scripts assume that 
the current directory is the "tspaces" directory that is created when you 
unzip (or untar) the distribution file.

<P>
We also have a 
<a href=#contrib>directory of TSpaces applications</a> that have been 
contributed by people outside of IBM.
 
<a name=server>
<H3>
TSpaces Server</H3>

<UL>This is not really an example program, but a script to start a TSpaces server.
All of the examples require that a TSpaces (TupleSpace) server be started
on either the local host or on a network attached host. So we have
provided a shell script that will start a TSpaces server on the local
host. Although all of the examples will run with the server running
on one system and the example on another, for simplicity, we will
assume that both are on the same system.
<BR>Before trying to start the server, you should make the 
current directory be the high level <strong>tspaces</strong> directory 
that is created when you unzip the distribution file.  Then you should invoke:
<BR>

<BR><TT><FONT SIZE=+1>bin\tspaces.bat</FONT></TT>
<p>
Additional information on starting the server and the available options
can be found in the 
<a href=progrguide.html#server>Programmer's Guide</a>.
</UL>


<!------------------------------------>
<H3><a name="whiteboard">Whiteboard</H3>
<!------------------------------------>


<UL>This is a very simple shared whiteboard application.&nbsp; Multiple
users can startup the whiteboard application or applet, all pointing to
the same server and the lines and points that are drawn on each white board
will be written to TSpaces when the "publish" button is pressed.&nbsp;
Since all Whiteboard&nbsp; applications have used the TSpaces "eventRegister",
they will all be notified and will display the new lines/points in their
own window. 
<p>
To invoke the Whiteboard applet from your browser:
<ul>

<p>
If you are viewing this page from the Almaden Web site and 
if you have started your own version of the TSpaces server 
on a local system, 
then manually enter the following URL into your browser to 
access the HTTP server that is built into TSpaces.
<pre>
  http://localname:8201/html/examples.html#whiteboard
</pre>
where "localname" is the name of the system that is running 
the TSpaces server. 
 
<p>
If you are already viewing this page by using the 
HTTP server</a>
that is built into TSpaces, then either:
<P> 
<a href="./wb_plugin.html" target=new >
<b>click here</b></a> to use the 
<a href="http://java.sun.com/products/plugin/" target=new ><b>Java PlugIn technology</b></a> 
from Sun, If you have not already installed
the Java PlugIn, you will be prompted to install it. 
<p>
or <a href="./whiteboard.html" target=new >
<b>click here</b></a> to use the native java support in Netscape or Microsoft IE.

If your browser does not support the Java PlugIn, then you can  invoke the Whiteboard  
via the appletviewer by issuing the following command:
<br>
<pre>
<TT><FONT SIZE=+1>bin\whiteboard  applet [hostname]</FONT></TT>

The parameters are:
   applet   - Causes the appletviewer to be used.
   hostname - Host name (defaults to localhost)
</pre>
<p>
It will also run as a Java application 
by issuing the following commands
<br>
<pre>
<TT><FONT SIZE=+1>bin\whiteboard   [hostname]</FONT></TT>

The parameters are:
   hostname - Host name (defaults to localhost)
</pre>

<p>
The most important part of the whiteboard demo is that it shows how
easy it is to write a multi-client application using TSpaces.  The web page
shows the important code fragments that 
implement the TSpaces client/server communication.
It also shows the interface to the HTTP Server that is built into the 
TSpaces Server for use in debugging.
</UL>


<H3>
MergeSort</H3>

<UL>This example shows a typical use of TSpaces for distributed computing.
The sample generates a number of random numbers and writes them to
TSpaces where they can be accessed and sorted by any number of SortThread
tasks that are running. The SortThread tasks can be on any
number of network systems.

<P>To invoke it issue the following commands:
<br>
<pre>
<TT><FONT SIZE=+1>bin\mergesort  [number]  [hostname]</FONT></TT>

The optional parameters are:
    number   - number of things to sort (defaults to 40)
    hostname - Host name (defaults to localhost)

</pre>
<BR>The script will automatically start a 2nd window to run an instance of SortThread.</UL>

<H3>
TClipboard</H3>

<UL>This example shows the use of TSpaces to implement a Global 
Clipboard that will work across any system connected to the network.

The TClipboard application will display a window with 4 Text areas. 
The top text area shows the contents of the System clipboard on the local system. The 
other 3 text areas show the contents of 3 buffers that are stored on 
TSpaces and can be accessed from any system.  
<p>
The idea is that the user has multiple clipboard windows -- one on each of
multiple machines. Something cut from one machine and placed into the clipboard automatically
appears in all of the clipboards. Thus, it becomes trivial to either share cut buffer contents between
users or share cut buffer contents between machines of the same user (for example, it's not
uncommon for a power user to have a UNIX machine side-by-side with an NT machine or a
Macintosh) 


<P>To invoke a copy of TClipboard on the local system, issue the following commands:
<br>
<pre>
<TT><FONT SIZE=+1>bin\copypaste   [-h hostname] [id]</FONT></TT>

The optional parameters are:
    id       - An id that represents a set of shared clipboards.  Could be your Userid.
    hostname - Host name (defaults to localhost)

</pre>
<P>To do anything interesting, you need to then start TClipboard on another system, 
or in the case of Unix, start it under another userid.  
Be sure that the "id" is the same on each instance of TClipboard if 
you want to share the clipboard.  
It is not recommended to start 2 instances of TClipboard on 
the same system because they will fight over ownership of the single 
System clipboard and give confusing results.
<p>
To do a copy/paste from an application of one system to another application 
on another system, do the following:
<ul>
<li>System_A:  Cut/copy (Ctrl-C) some String of data from any application.
<li>System_A:  Verify that it shows up in the System Clipboard window of TClipboard
<li>System_A:  Copy the data into Buffer 1 (using the Publish button)
<li>System_B:  Verify that the data appears in Buffer 1 on System_B's TClipboard
<li>System_B:  Copy the data from Buffer 1 to the System clipboard using the Read button.
<li>System_B:  Paste(Cntrl-V) the data into any application on System_B 
</ul>
Or you can select the <strong>AutoRead</strong> and <strong>AutoPublish</strong> options on 
each system and whatever you <strong>copy</strong> or <strong>cut</strong> on one system 
will automatically appear in the 
system clipboard of the other system.   Now you can iconify the java applications and enjoy 
your new Global clipboard facility.
</UL>

<H3>
URLCopy</H3>
<UL>This is an example of how to use TSpaces to copy the data that is pointed to
by a URL along with a Tuple.  
The
<a href="./javadoc/com/ibm/tspaces/URLCopy.html" target=new>
<b>URLCopy</b></a> object has been provided as special TSpaces aware object
that represents a URL or File object that can be cpopied between TSpaces clients via 
TSpaces services.
<P>To invoke the example, issue the following command:
<br>
<pre>
<TT><FONT SIZE=+1>bin\urlcopy [-D] [-h tsserver]  url </FONT></TT>

  -D           -  display debugging msgs
  -h tsserver  - specify TSpaces server. Default is "localhost"
  url          - Valid URL or filename.  Default is "file:/c:/test.txt"

</pre>
<p>
<b<Note:</b> To run this example you must first turn on the FileStore facility in the
server by specifing the directory where copied files will be stored.  
This is specified in the tspaces.cfg file.  Restart the server after making this change.

</UL>


<p>
<H3>
Rhonda</H3>

<UL>This is an example of the use of the Rhonda operator in TSpaces.
The rhonda operator takes a tuple as an argument and atomically 
swaps two matching tuples. 
That is, if process 1 and process 2 perform rhondas with Tuples that have the 
same templates, the tuple that is returned to them is the other processes 
tuple. 
This is useful for atomic synchronization. 
<p>
The sample RockPaperScissors example starts two Java TSpaces applications each talking 
to the same TSpaces server.  These two applications then play the Rock PaperScissors game.
by issuing a "Rhonda" command with a template that contains their name and their choice of 
"R","P", or "S".  They then look at the tuple that is returned from the other player to 
determine if they won, lost or tied.  

<P>To invoke it issue the following commands:
<br>
<pre>
<TT><FONT SIZE=+1>bin\rhonda</FONT></TT>
</pre>
<p>
In case you are not familiar with the game RockPaperScissors 
(also know as RoShamBo),  each player at the count of three, puts out 
their hand with a fist(Rock), a flat palm(Paper) or two fingers(Scissors).  
The winner is determined by the following rules:
 <ul>
  <li>Rock breaks Scissors
  <li>Scissors cut Paper
  <li>Paper covers Rock
 </ul>  
</UL>

         

<H3>
Simple</H3>
<UL>
In contrast to the previous examples which had limited but useful functions, the Simple 
set of examples are only there to demonstrate how one would might write some simple 
TSpaces client code.  By keeping the examples, very small and simple, it is hoped 
that it will be easy to learn by example. 
<P>To run all of the Simple examples, issue the following command:
<br>
<pre>
<TT><FONT SIZE=+1>bin\simple</FONT></TT>
</pre>
This will run the examples that are described below and the examples that are 
described in the Programmer's Guide. 
<p> 
<h3>Description of Simple Examples</h3>
<ul>
<li>Simple1<br>
This example writes a couple of tuples (an ordered set of fields) to the TSpaces server
and then reads the tuples back using 2 different methods. 
<p>
<li>SubclassExample1<br>
This example is similar to <strong>Simple1</strong> but instead of directly creating and 
querying the Tuple directly, an object is created that extends SubclassableTuple and hides 
all of the ugly Tuple manipulation inside the object.    
<p>
<a name=superheros>
<li>SuperHeros<br>
This example was inspired by a published paper on TSpaces.  
It shows the use of "named fields" in a Tuple and the query
operations that are available with a TSpaces server that implements the TSpaces 
Main Memory database.
<p>
One of the differentiating features of TSpaces is that it builds an index on 
each named field in a tuple.  
This enables clients to request tuples based solely on values in fields with a given name, 
regardless of the structure of the rest of the tuple 
(or even the position of the named field within the tuple).  
For example, an index query of the form ("foo",8) will select all tuples (of any format) 
containing a field named "foo" with the integer value 8.  
It is also possible to specify a range of values to be found in the index.
<p>
The current implementation of TSpaces provides four types of queries: 
Match, Index, And and Or queries.  
A Match query performs structural or object compatibility matching (depending on its argument), 
while an Index query performs a named-field query.  
And and Or queries can be used to combine these and build complex query trees.  
The SuperHeros example shows an example of each of these queries. 

</UL>
</UL>
<a name=worker></a>
<p>
<H3>Worker</H3>
<UL>

This class implements a TupleSpace worker that will take a 
Runnable object from a space and run it. 
<p>
This class is inspired by the book <i>MirrorWorld</i> by David Gelernter.
This implements his idea of clients that will grab tuples that contain 
eval() functions, run the procedure indicated by the eval() and then 
return the answer to the tuplespace.  This does not, however, work the same
as the <b>eval</b> operator in the Linda system.
<p>
In our case, the eval() function is represented by a Tuple that has a Field 
containing a Java  Object that has an Eval interface.  
The Eval interface extends Runnable and Serializble. Eval defines one method,
getResult() that returns a Serializable Object.
<p>
A client that has work that can be processed by other randon processors will 
write a Tuple to the <b>Worker</b> space that has  
the following format:
<pre>
  Field 0   String  "Worker"   (WORKER_KEY)
  Field 1   String  type       Any type string that the user wants to assign
  Field 2   String  uniqueid   Any Id that is unique.  We use this to 
                               reflect back the result.
  Field 3   Eval    object     Any Object that contains a run() method that 
                               can be started.
</pre>
There can be one or more Worker clients on many machines in the network, all of 
which are waiting for work Tuples in the above format.
When it get one of these Tuples, it will start a thread that will invoke the 
run() method for the Eval object. When the run method ends, it will
regain control, use the getResult method to get the result and write the 
the following Tuple back into the space.
<pre>
  Field 0   String  "WorkerResult"   (WORKER_RESULT)
  Field 1   String  type       Copied from input Tuple
  Field 2   String  uniqueid   Copied from input Tuple
  Field 3   Serializable result  Object that contains the result 
            
</pre>

The program that is creating the work to be done will do the following:
Assume that WorkerTest is a class whose run method does the work to be shared
<pre>
   TupleSpace work = new TupleSpace(Worker._TSNAME,tsHost);
   
   WorkerTest wt = new WorkerTest(param1,param2);
   Tuple workTuple = new Tuple(Worker.WORKER_KEY,"WorkerTest","id1",wt);
   work.write(workTuple);
   Tuple template = new Tuple(Worker.WORKER_RESULT,"WorkerTest","id1",new Field(Serializable.class));
   Tuple result = work.waitToTake(template);

</pre>        
The constructor for WorkerTest would store any parameters needed by the 
run method as instance variables.
<p>
When the Worker client takes one of the above Tuples from the space,
it starts a new thread with the following code:
<pre>
       Eval task = (Eval)workTuple.getField(3).getValue();
       String type = (String)workTuple.getField(1).getValue();
       String id = (String)workTuple.getField(2.getValue();
       Thread t = new Thread(task,type+"-"+id);
       t.start();
       t.join();
</pre> 
When the run() method completes, we get back control at the join() and 
we will write back a Tuple that contains the result 
<p>
Note that your application could also use the Eval interface above to implement 
your own Tuples that could share processing.  For example, you could have
a client that passes the input data and run method that produces a chart 
instead of passing the formated chart.

<p>
The intent is that one would start a worker thread on each of the machines 
in a network and allow anyone that needed extra compute power, to use Eval 
objects to spread the work to other machines.  
<p> 
If you start a Worker thread to share your CPU processor, you would want 
to be assured that the Eval threads run in a Java sandbox that it has 
restrictions similar to applets that run in a browser.
With JDK 1.2, This is relatively easy to do.
The distributed <b>worker.bat</b> file can be modified to specify the 
following (on a single line):
<pre>
java -Djava.security.manager 
     -Djava.security.policy=file:/c:/.java.policy 
      com.ibm.tspaces.services.Worker %1 %2 %3 %
</pre>
The file "c:/.java.policy" should have the following contents:
<pre>

grant {
  // allows anyone to connect  on un-privileged ports
  permission java.net.SocketPermission "*:1024-", "listen, connect, resolve";
};

</pre>
The above combination will tell Java to run with a Security manager and only grant
permission to connect to un-privileged ports on any machine.  
One could modify the above to restrict the machines or perhaps grant other 
permissions. 
<p>
An example of the use of <b>Worker</b> is in SortMerge2.java which uses 
the Merger.java object to do the merge/sort using Worker threads.  
This code can be found in the examples/sortmerge directory.

</UL>


<a name=tsui></a>
<p>
<H3>TupleSpaceUI</H3>
<UL>
<b>TupleSpaceUI</b> is a simple little command line tool that allows you to 
dynamically read and write Tuples to an space. 
<p>
To invoke the TupleSpaceUI, type:
<pre>
cd /tspaces
set classpath=.\classes;.\lib\tspaces.jar
java com.ibm.tspaces.examples.tsui.TupleSpaceUI
</pre>
<p>
This will bring up a prompt, at which you can type various commands, (type h for
help), if you are familiar with the tuplespace commands, these enable you to
manually enter a tuple and issue one of the commands with it (read, write, scan,
take).  After choosing one of these commands, you will be prompted to create a
tuple.  This is done one field at a time, first by entering the type of the
field (only a few primitive types are supported: int, string, boolean, double,
tuple), and then the value.  If you enter a tuple as the type of the field,
the program will automatically descend into that new tuple and prompt you for
fields in there.  For further help, type 'h', you can add and change fields, but
removal of fields is not yet supported.  After you have the desired fields, type
'x' to perform the selected action on the tuple.  If the action is a read, take
or scan, then the returned tuple(s) will be displayed.

You can also write XML documents and perform basic XQL queries, by choosing wxml
or qxml from the main menu.  They prompt you for a file name where the XML/XQL
can be found or you can type it in if you desire.  You will need the xml4j.jar file
in your classpath however.


</UL>

<p>
<a name=x10></a>
<H3>X10 Support</H3>

<UL>
X-10 is a technology that communicates to devices in the home by sending and 
receiving signals over the home power line wiring.
A typical system has multiple Modules that have lights or appliances 
connected to them.   Also plugged into the home wiring are one or more 
controllers that have the abiltiy to send commands to modules. 
One of the controllers is a computer interface that plugs into the 
home wiring and has a connection to the serial port on a 
computer. Another typical controller is a tranceiver that 
will pick up radio frequency (RF) commands from devices like 
motion detectors and handheld remote controls. 
For more information see the 
<a href="http:/www.x10.com" >www.x10.com</a> site.
<p>
We have written a Java monitor application that will connect to the 
serial port and both watch for X10 events and when instructed send 
a X10 command to a module.  The X10 events are reflected 
to a TSpaces server where it will then maintain the status of a 
module (The light is on or off).  Comamnds for an X10 device can 
be written to TSpaces and the monitor will pick up the command and issue it 
to the device via the computer interface.  
<p>
As a result, one can write very simple java programs to interface to X10 
without having to learn the complex serial port interface and the devices
can be monitored and controlled from any site in the network.  
<p>
To make this clearer, I will describe the demo setup that I have implemented.
The source for this is in <i>tspaces/examples/x10</i>.
In my home office,  I have a motion detector that can sense when I am 
in the office 
and a light that is plugged into an X10 Module.  
I run the TSX10 application on my 
office computer that has a X10 PC interface.  When the motion detector detects 
motion it sends "A3 On", the TSX10 application sees the event and 
updates a tuple to < "X10Status", "A3", "ON" >.  
When the motion detector detects that there is no motion, it sends "A3 off"
and TSX10 changes the tuple to < "X10Status", "A3", "OFF" > 
I also have an applet that can run on any browser.  It will connect to the 
same TSpaces server and issue Read <"X10Status","A3",*> and get back the 
current status and display whether I am in the office.  
<p>
The same demo  applet also has Lamp On and Off buttons.  When the user presses 
the ON button, a tuple <"X10Cmd","A2","On"> is written to the space.  
X10Monitor is waiting for "X10Cmd" tuples and when one appears in the space it 
will be read and in this case,  
the lamp with device address "A2" will be turned on.  
<p>
This test setup does not do anything really useful, but it is easy to see how one 
might be able to use this technology.  Some examples:
<ul>
<li>If you tend to leave work at 
very different hours, just before you leave your office 
you could turn on your heating system using the X-10 thermostat module.   
<li>With the Palm Pilot PDA support for TSpaces, you could use your Pilot 
to control all of the lights in your house or use it as an expensive 
garage door opener.  
<li>If someone walks up to your front door, you could trigger a camera to take 
a picture, store it  and based on whether you were in your home office, 
notify you on your desktop or 
using the TSpaces pager support, send you a page. 
<li>Since the basic X10 kit comes with a multipurpose remote control 
that can control traditional devices like a TV and also will issue 
X10 commands.  So you could define address "A5" as a virtual devices.
Then "A5" is turned on by the remote control, it would write a Tuple to 
TSpaces.  You could have another TSpaces client running anywhere 
on the network that would be watching for an "A5 on" event and when found 
it would take some action.  So while you are watching TV, using the remote,
you could have a TSpaces client check your mail and if any present, flash a light in your 
living room.
<li><b>Getting X10 running with TSpaces</b><br>
<ul>
<li>Download the 
<a href="http://java.sun.com/products/javacomm/index.html">Java Communication API</a>
 product and install it as instructed.

<li>Modify the <b>bin\x10.bat</b> file to specify <b>comm.jar</b> in the classpath.

<li>Invoke <b>bin\x10.bat</b> 
</ul>
</ul>
</UL>
<p>
<hr>
<p>
<a name=contrib></a>

<H1>Contributed TSpaces Applications</H1>
<UL>
The tspaces/contrib directory contains applications that have been contributed by 
people outside of IBM.  Please contact the author directly if you have
comments or problems with the contributed code. 
<p> 

<ul>
<li>ITC Client/Server
<p>
This is a chatroom facility that uses TSpaces instead of IRC.
<p>
Written by Kevin Eustice 
<a href=mailto:kevin@cs.hmc.edu>kevin@cs.hmc.edu</a>
</ul>

</UL>

<!----------------------------------------------------------------->
<hr>
<! ------------------------------------------------------------------------->
[
<a href="../index.html" target=_top>
TSpaces home page </a>
]

</BODY>
</HTML>
